package com.wanmait.happyheating.Async;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wanmait.happyheating.pojo.Ordersinfo;
import com.wanmait.happyheating.service.OrdersinfoService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.DelayQueue;

/**
 * @Author : 韩丕文
 * @Description :
 **/

@Service
public class TestAsyncServiceImpl implements com.wanmait.happyheating.Async.TestAsyncService {

    @Resource
    OrdersinfoService ordersinfoService;
    @Async("getExecutor")
    @Override
    public String testNotice(int[] taskDelayMill,Integer id) throws InterruptedException, IOException {

        System.out.println(Thread.currentThread().getName() + "   -------正在异步执行任务------" + new Date());

        DelayQueue delayQueue = new DelayQueue();

        //数组的length大小就是额外需要发送的通知数
        int taskSum=taskDelayMill.length;

        //将每一次发送通知的间隔时间都对应创建一个延迟设置类,放入延迟队列delayQueue里
        for (int i=0;i<taskSum;i++){
            delayQueue.put(new DelayElement(taskDelayMill[i]));
        }

        System.out.println("开始时间：" +  DateFormat.getDateTimeInstance().format(new Date()));
        while (!delayQueue.isEmpty()){
            // 执行延迟任务
            System.out.println("现在执行未接单延迟任务");

            //模拟调用API,通知发货,得到发货结果 成功或失败

            String result = getNoticeResult(id);

            System.out.println("通知发货的结果是："+result);
            if (!result.equals("success")){

                System.out.println("任务执行中："+delayQueue.take());
            }else {

                break;
            }
        }
        //查询订单结果

        System.out.println("通知任务不需要再发,订单结果已经确定");

        System.out.println("结束时间：" +  DateFormat.getDateTimeInstance().format(new Date()));




        return "success";
    }


    //模拟发货通知的结果
    public String getNoticeResult(Integer id) throws IOException {

        //模拟调用通知发货API接口,获取返回结果
        LambdaQueryWrapper<Ordersinfo>ordersinfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersinfoLambdaQueryWrapper.eq(Ordersinfo::getId,id);
        Ordersinfo ordersinfo=ordersinfoService.getOne(ordersinfoLambdaQueryWrapper);
            if(ordersinfo.getId()!=null){
                String[] strs={"--该订单已发送给工作人员分配--"};
                return  RandomStr(strs);
            }
            else {
                String[] strs={"--该订单已抢单成功--"};
                return  RandomStr(strs);
            }

        




    }

    //随机返回字符串数组中的字符串
    public static String RandomStr(String[] strs){
        int random_index = (int) (Math.random()*strs.length);
        return strs[random_index];
    }


}